package dome1.network;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Scanner;

public class TcpEchoClient {
    private Socket socket = null;

    public TcpEchoClient(String severIp, int serverPort)throws IOException {
        socket = new Socket(severIp,serverPort);
    }
    public void start(){
        System.out.println("客户端启动！");
        Scanner scanner = new Scanner(System.in);

        //先写入流数据
        try(InputStream inputStream = socket.getInputStream();
            OutputStream outputStream = socket.getOutputStream()) {

            Scanner scannerNetwork = new Scanner(inputStream);
            //创建循环
            while (true) {
                //1、从控制台读取数据
                System.out.println("请输入要发送的数据");
                String request = scanner.next();

                //2、要把请求发给服务器，发送的请求要带有\n（空格）,和服务器的scanner.next（读取到空格符号就结束）是对应的，
                //由于上述的request获取到的数据无\n,所以要手动添加
                request += "\n";
                outputStream.write(request.getBytes());//转换为Byte序列

                //3、从服务器读取响应
                if(!scannerNetwork.hasNext()) {
                    break;
                }
                String response = scannerNetwork.next();

                //4、把响应显示在控制台上
                System.out.println(response);

            }
        }catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws IOException {
        TcpEchoClient tcpEchoClient = new TcpEchoClient("127.0.0.1",9090);
        tcpEchoClient.start();
    }
}
